package com.cy.lib.image;/**
 * Created by CY on 2015/5/7.
 */

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author CY
 * @title 保存图片
 * @date 2015/5/7
 * @qq 568305883
 * @email tmxdyf@163.com
 */
public class SaveTarget extends AsyncTask<Bitmap, Object, Object> implements Target {

    File mSaveFile;

    OnSaveListener mListener;

    boolean isSync;//是否同步

    public SaveTarget(File file, boolean isSync) {
        this(file, null, isSync);
    }

    public SaveTarget(File targetFile, OnSaveListener listener, boolean isSync) {
        mSaveFile = targetFile;
        mListener = listener;
        this.isSync = isSync;
    }

    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        if (isSync) {
            save(bitmap);
        } else {
            execute(bitmap);
        }
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {

    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {

    }

    @Override
    protected Object doInBackground(Bitmap... bitmaps) {
        save(bitmaps[0]);
        return null;
    }

    private void save(Bitmap bitmap) {
        try {
            if (!mSaveFile.exists()) {
                if (!mSaveFile.getParentFile().exists()) {
                    mSaveFile.getParentFile().mkdirs();
                }
                mSaveFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(mSaveFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            mSaveFile.delete();
        }
        bitmap.recycle();
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        if (mListener != null) {
            if (mSaveFile.exists()) mListener.finish(mSaveFile);
            else mListener.error(mSaveFile);
        }
    }

    public interface OnSaveListener {
        public void finish(File file);

        public void error(File file);

    }
}
